<?php 
namespace Emos\Field;

use Emos\Common;
use Emos\Db;

class LatLng extends AbstractControl {
    var $height = 300;    
    var $zoom = 8;
    
    public function __construct($zoom=8) {
        $this->zoom = (int)$zoom;
    }
    
    public function setValueFromRecord(array $record) {
        $this->value = array(
            'lat' => @$record[$this->dbName.'_lat'],
            'lng' => @$record[$this->dbName.'_lng']
        );
    }
    
    public function update() {    
        $newValue = $this->getPost();
        if($newValue === null) {            
            return array(
                $this->dbName.'_lat' => new Db\SqlExpression("NULL"),
                $this->dbName.'_lng' => new Db\SqlExpression("NULL")
            );            
        }
        else {
            return array(
                $this->dbName.'_lat' => (double)$newValue['lat'],
                $this->dbName.'_lng' => (double)$newValue['lng']
            );        
        }        
    }            
    
    protected function isNull() {
        return (($this->value['lat'] === null) || ($this->value['lng'] === null));
    }    
    
    public function html() {        
        return 
            "<div class='latLng' data-zoom='{$this->zoom}'>".
            "<div class='inputs'>".
            Common::t('lat')." <input type='text' class='lat' name='{$this->htmlName}[lat]' value='".$this->value['lat']."' /> &nbsp; ".
            Common::t('lng')." <input type='text' class='lng' name='{$this->htmlName}[lng]' value='".$this->value['lng']."' />".
            "</div>".
            "<div class='map' style='height:{$this->height}px'></div>".
            "</div>";
            
    }   

    public function getDdlFields() {
        return array(
            "{$this->dbName}_lat" => "DOUBLE",
            "{$this->dbName}_lng" => "DOUBLE"
        );
    }         
}